import os
import socket
import json

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

class Server(object):
    file_path = os.path.join(BASE_DIR, 'user.txt')
    msg_code = {
        200: "register successful",
        # 200: "注册成功",
        201: "user exits",
        300: "login successful",
        301: "user or password error"
    }

    def __init__(self, ip, port):
        self.ip = ip
        self.port = port
        self.sock = socket.socket()
        self.sock.bind((self.ip, self.port), )
        self.sock.listen(5)
        # 如果用户文件不存在，就创建
        if not os.path.isfile(self.file_path):
            open(self.file_path, 'wb').close()


    def register(self, data):
        """ 专门负责注册逻辑的方法 """
        print('register', data)
        f = open(self.file_path, 'r', encoding='utf8')
        for line in f:
            # line: zhangkai|202cb962ac59075b964b07152d234b70
            user, pwd = line.strip().split('|')
            if user == data['user']:  # 该用户已注册
                data['code'] = 201
                data['code_content'] = self.msg_code[201]
                break
        else:  # 表示用户没有注册过，可以正常写文件了
            f.close()
            f = open(self.file_path, 'a', encoding='utf8')
            f.write(f'{data["user"]}|{data["pwd"]}\n')
            f.close()
            data['code'] = 200
            data['code_content'] = self.msg_code[200]

        self.conn.send(json.dumps(data).encode())

    def login(self, data):
        """ 专门负责登录逻辑的方法 """
        print('login', data)
        f = open(self.file_path, 'r', encoding='utf8')
        for line in f:
            # line: zhangkai|202cb962ac59075b964b07152d234b70
            user, pwd = line.strip().split('|')
            if user == data['user'] and pwd == data['pwd']:  # 用户名和密码校验成功
                data['code'] = 300
                data['code_content'] = self.msg_code[300]
                break
        else:  # 用户名或者密码校验失败，需要重新登录
            data['code'] = 301
            data['code_content'] = self.msg_code[301]
        f.close()
        self.conn.send(json.dumps(data).encode())

    def handler(self):
        """
        专门用于跟客户端转发消息的方法
        :return:
        """
        while True:  # 连接循环
            print('等待新客户端的链接....')
            self.conn, addr = self.sock.accept()
            while True:  # 通信循环
                print(f'等待客户端发送消息....')
                try:
                    msg = self.conn.recv(1024).decode()
                    if msg:
                        js_data = json.loads(msg)
                        print(js_data)
                        if hasattr(self, js_data['action_type']):
                            method = getattr(self, js_data['action_type'])
                            method(js_data)
                        else:
                            self.conn.send('不支持的方法'.encode())
                    else:
                        print('客户端退出')
                        break
                except ConnectionResetError as e:
                    print('当前客户端异常断开', e)
                    break
            self.conn.close()

        self.sock.close()


if __name__ == '__main__':
    obj = Server('127.0.0.1', 8887)
    obj.handler()
